//
//  RootViewController.m
//  reacticons
//
//  Created by Nong Nghia on 4/14/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import "DataManagement.h"
#import "TestFlight.h"
#import "ImageListViewController.h"
#import "HeaderViewController.h"
#import "EGOImageView.h"
#import "AppDelegate.h"
#import "EGOImageLoader.h"

@interface RootViewController (internal)


@end

@implementation RootViewController

@synthesize itemPerRow = _itemPerRow;
@synthesize parentID = _parentID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [searchResult release];
    [folderList release];
    [homeSearchBar release];
    [itemGridView release];
    [super dealloc];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [TestFlight passCheckpoint:@"RootViewController - viewDidAppear - INIT_FROM_SECOND_TIME"];
    NSString *initInfo=[[NSUserDefaults standardUserDefaults] objectForKey:@"INIT_DATA"];
    if ([initInfo isEqualToString:@"SUCCESS"]) {
        [TestFlight passCheckpoint:@"RootViewController - viewDidAppear"];
        folderList=[[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] getCategories];
        [itemGridView reloadData];
        HeaderViewController * headerController = [[HeaderViewController alloc] init];
        headerController.delegate=self;
        [itemGridView setHeaderView:headerController.view];
    }    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[self navigationController] setNavigationBarHidden:NO animated:NO];
    [self.navigationItem setTitle:@"Reacticons"];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [TestFlight passCheckpoint:@"RootViewController - viewDidLoad"];

    [self.view setBackgroundColor:[UIColor blackColor]];
    self.navigationController.navigationItem.leftBarButtonItem=nil;
    self.navigationController.navigationItem.backBarButtonItem=nil;    
    
//    UIBarButtonItem * customSettingsBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"reorderring.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(settingsButtonClick:)];
    
    UIBarButtonItem * searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(settingsButtonClick:)];
    
    [self.navigationItem setRightBarButtonItem:searchButton];
    [searchButton release];
    
    homeSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, -40, 320, 40)];
    [homeSearchBar setBarStyle:UIBarStyleBlackOpaque];
    
    [self.view addSubview:homeSearchBar];
    [homeSearchBar setDelegate:self];
    
    folderList = [[NSMutableArray alloc] init];
    searchResult = [[NSMutableArray alloc] init];
    
    DataManagement * dataManager = [[[DataManagement alloc] init] autorelease];
    NSString *initInfo=[[NSUserDefaults standardUserDefaults] objectForKey:@"INIT_DATA"];
    if (![initInfo isEqualToString:@"SUCCESS"]) {
        [TestFlight passCheckpoint:@"RootViewController - viewDidLoad - INIT_FIRST_TIME"];
        [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] showInitLoadingView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDatabaseFinish:) name:kUpdateDatabaseFinishNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDatabaseFailed:) name:@"kDownloadListFromTumblrFailedNotification" object:nil];
        [[(AppDelegate *)[[UIApplication sharedApplication] delegate] dataManager] requestListItemFromTumblr];
    }
    else {
        [TestFlight passCheckpoint:@"RootViewController - viewDidLoad - INIT_FROM_SECOND_TIME"];

        folderList=[dataManager getCategories];
        searchResult = [folderList mutableCopy];
        [itemGridView removeFromSuperview];
        [itemGridView release];
        itemGridView=nil;
        itemGridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, 320, 460-44-49)];
        HeaderViewController * headerController = [[HeaderViewController alloc] init];
        headerController.delegate=self;
        [itemGridView setHeaderView:headerController.view];
        [self.view addSubview:itemGridView];
        [itemGridView setBackgroundColor:[UIColor clearColor]];
        [itemGridView setDelegate:self];
        [itemGridView setDataSource:self];

        NSInvocationOperation *invoOp=[[NSInvocationOperation alloc] initWithTarget:[(AppDelegate *)[[UIApplication sharedApplication] delegate] dataManager] selector:@selector(requestListItemFromTumblr) object:nil];
        [[(AppDelegate *)[[UIApplication sharedApplication] delegate] appQueue] addOperation:invoOp];

    }

    settingBtn =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"setting_bar_icon"] style:UIBarButtonItemStyleBordered target:self action:@selector(btnWasClicked:)];
    
//    settingBtn=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(btnWasClicked:)];
    [settingBtn setTag:12];
    [self.navigationItem setLeftBarButtonItem:settingBtn];
    [settingBtn release];
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Buttons On Click

- (void)settingsButtonClick:(id)sender
{
//    UIBarButtonItem * barButton = sender;
    headerShown = !headerShown;
    CGRect searchBarFrame;
    CGRect gridViewFrame;
    
    if (headerShown) 
    {
        searchBarFrame = CGRectMake(0, 0, 320, 40);
        gridViewFrame = CGRectMake(0, 40, 320, 460-44-40-49);
    }
    else
    {
        searchBarFrame = CGRectMake(0, -40, 320, 40);
        gridViewFrame = CGRectMake(0, 0, 320, 460-44-49);
    }
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [homeSearchBar setFrame:searchBarFrame];
    [itemGridView setFrame:gridViewFrame];
    [UIView commitAnimations];
}

#pragma mark - Grid View Data Source

- (CGFloat)gridView:(UIGridView *)gridView heightForRowAtIndex:(NSInteger)rowIndex
{
    return 100;
}

- (NSInteger)numberOfCellsInGridView:(UIGridView *)gridView
{
    [TestFlight passCheckpoint:@"RootViewController - numberOfCellsInGrideView"];
    TFLog(@"RootViewController - numberOfCellsInGrideView:%d",[searchResult count]);

    return [searchResult count];
}

- (NSInteger)gridView:(UIGridView *)gridView numberOfCellsPerRowInRow:(NSInteger)rowIndex
{
    return 3;
}

- (GridViewCell*)gridView:(UIGridView *)gridView cellAtIndex:(NSInteger)cellIndex
{

    UIGridViewCell_DownloadImage * cell = [[[UIGridViewCell_DownloadImage alloc] initWithFrame:CGRectZero] autorelease];
    
    Items * category = [searchResult objectAtIndex:cellIndex];
//    TFLog(@"RootViewController - cellAtIndex:[%d]%@",cellIndex,category.field3);

    [cell.imageView setContentMode:UIViewContentModeScaleAspectFill];
    if (category.field3 != nil)
        [cell setImageURLString:category.field3];   
    
    [cell.textLabel setText:[NSString stringWithFormat:@"%@", category.name]];
    [cell setAccessoryType:UIGridViewCellAccessoryNone];
    
    return cell;
}

#pragma mark - Grid View Delegate

- (void)gridView:(UIGridView *)gridView targetIndexCellForMoveFromIndexCell:(NSInteger)sourceIndexCell toProposedIndexCell:(NSInteger)proposedDestinationIndexCell
{
    NSMutableArray * bufferArray = [[NSMutableArray alloc] init];
    if (sourceIndexCell == proposedDestinationIndexCell) {
        return;
    }
    if (sourceIndexCell < proposedDestinationIndexCell) {
        for (int i = 0; i < sourceIndexCell; i++) {
            [bufferArray addObject:[folderList objectAtIndex:i]];
        }
        for (int i = sourceIndexCell; i < proposedDestinationIndexCell; i++) {
            Items * item = [folderList objectAtIndex:(i+1)];
            [item setField10:[NSNumber numberWithInt:i]];
            [bufferArray addObject:item];
        }
        [bufferArray addObject:[folderList objectAtIndex:sourceIndexCell]];
        for (int i = proposedDestinationIndexCell+1; i < folderList.count; i++) {
            [bufferArray addObject:[folderList objectAtIndex:i]];
        }
    }
    else if (sourceIndexCell > proposedDestinationIndexCell) {
        for (int i = 0; i < proposedDestinationIndexCell; i++) {
            [bufferArray addObject:[folderList objectAtIndex:i]];
        }
        for (int i = proposedDestinationIndexCell; i < sourceIndexCell; i++) {
            Items * item = [folderList objectAtIndex:(i+1)];
            [item setField10:[NSNumber numberWithInt:i]];
            [bufferArray addObject:item];
        }
        [bufferArray addObject:[folderList objectAtIndex:proposedDestinationIndexCell]];
        for (int i = sourceIndexCell+1; i < folderList.count; i++) {
            [bufferArray addObject:[folderList objectAtIndex:i]];
        }
    }
    
    [folderList removeAllObjects];
    folderList = [bufferArray mutableCopy];
    searchResult = [folderList mutableCopy];
    [bufferArray release];
    [itemGridView reloadData];
}

- (void)gridView:(UIGridView *)gridView didSelectedCellAtIndex:(NSInteger)cellIndex
{
//    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] showLoadingView];
    
    Items * item = [searchResult objectAtIndex:cellIndex];
    ImageListViewController * rootView = [[ImageListViewController alloc] init];
    [rootView setParentID:[NSString stringWithFormat:@";%@;",item.name]];
    [rootView setTitle:item.name];
    [self.navigationItem setTitle:@"Categories"];
    [self.navigationController pushViewController:rootView animated:YES];
}

- (void)gridView:(UIGridView*)gridView didLongPressCellAtIndex:(NSInteger)cellIndex
{
    
}

#pragma mark - Update View After Update Database

-(void)updateDatabaseFinish:(NSNotification*)notification{
    self.navigationItem.leftBarButtonItem=nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kUpdateDatabaseFinishNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kDownloadListFromTumblrFailedNotification" object:nil];

    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] stopLoadingView];
    DataManagement * dataManager = [[[DataManagement alloc] init] autorelease];
    folderList=[dataManager getCategories];    
    searchResult = [folderList mutableCopy];
    
    itemGridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, 320, 460-44-49)];
    HeaderViewController * headerController = [[HeaderViewController alloc] initWithNibName:@"HeaderViewController" bundle:nil];
    headerController.delegate=self;
    [itemGridView setHeaderView:headerController.view];
    [self.view addSubview:itemGridView];
    [itemGridView setBackgroundColor:[UIColor clearColor]];
    [itemGridView setDelegate:self];
    [itemGridView setDataSource:self];

    [[NSUserDefaults standardUserDefaults] setValue:@"SUCCESS" forKey:@"INIT_DATA"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(void)updateDatabaseFailed:(NSNotification*)notification{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kDownloadListFromTumblrFailedNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kUpdateDatabaseFinishNotification object:nil];

    [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] stopLoadingView];
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Error Connection" message:@"Download List From Tumblr failed.\nPlease check your connection!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
    UIBarButtonItem *refreshBtn=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(btnWasClicked:)];
    [refreshBtn setTag:11];
    [self.navigationItem setLeftBarButtonItem:refreshBtn];
    [refreshBtn release];
}

-(IBAction)btnWasClicked:(id)sender{
    if ([sender tag]==11) {
        self.navigationItem.leftBarButtonItem=settingBtn;
        [[(AppDelegate*)[[UIApplication sharedApplication] delegate] loadingView] showInitLoadingView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDatabaseFinish:) name:kUpdateDatabaseFinishNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDatabaseFailed:) name:@"kDownloadListFromTumblrFailedNotification" object:nil];

        [[(AppDelegate*)[[UIApplication sharedApplication] delegate] dataManager] requestListItemFromTumblr];
    }
    if ([sender tag]==12) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Cached Data" message:@"Total amount used: ## MB\nClear cached images?" delegate:nil cancelButtonTitle:@"CANCEL" otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
    }
}
#pragma mark - Search Bar Delegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [homeSearchBar setShowsCancelButton:YES animated:YES];
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    [homeSearchBar setShowsCancelButton:NO animated:YES];
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [searchResult removeAllObjects];
    searchResult = [folderList mutableCopy];
    [itemGridView reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSString * sText = [[NSString alloc] initWithFormat:@"%@",[searchText lowercaseString]];
    
    if (!searchResult) {
        searchResult = [[NSMutableArray alloc] init];
    }
    [searchResult removeAllObjects];// remove all data that belongs to previous search
    
    if([searchText isEqualToString:@""] || searchText==nil){
        
        [itemGridView reloadData];
        
        return;
        
    }
    
//    NSInteger counter = 0;
    
    for(Items * item in folderList)
    {
        
        NSString *str = [item.name lowercaseString];
        
        NSRange r = [str rangeOfString:sText];
        
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
        
        if(r.location != NSNotFound)
        {
            if(r.location == 0)//that is we are checking only the start of the names.
                
            {
                [searchResult addObject:item];
            }
            
        }
        
//        counter ++;
        [pool release];
    }
    
    [sText release];
    
    [itemGridView reloadData];
    
}

-(void)clickedHeaderBtn:(id)sender{
    NSLog(@"clicked");
    switch ([sender tag]) {
        case 0:
            //  Call the view of all images
            NSLog(@"Folder of all images");
            ImageListViewController * rootView = [[ImageListViewController alloc] init];
            [rootView setParentID:[@"recentlyAdded" retain]];
            [rootView setTitle:@"Recently Added"];
            [self.navigationController pushViewController:rootView animated:YES];
            [rootView release];
            break;
            
        case 1:
            //  Call the view of recent used images
            NSLog(@"Folder of recent used images");
            ImageListViewController * rootView2 = [[ImageListViewController alloc] init];
            [rootView2 setParentID:@"recentlyUsed"];
            [rootView2 setTitle:@"Recently Used"];
            [self.navigationController pushViewController:rootView2 animated:YES];
            [rootView2 release];
            break;
            
        default:
            break;
    }
    

}

@end
